package www.ld.com.controller;

import cn.hutool.core.bean.BeanUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import www.ld.com.core.group.InsertGroup;
import www.ld.com.core.group.UpdateGroup;
import www.ld.com.domain.R;
import www.ld.com.domain.department.pojo.DepartmentPO;
import www.ld.com.domain.department.query.DepartmentQuery;
import www.ld.com.domain.department.vo.DepartmentVO;
import www.ld.com.domain.department.vo.InDepartmentVO;
import www.ld.com.domain.department.vo.OutDepartmentVO;
import www.ld.com.domain.vo.SelectTreeVO;
import www.ld.com.service.DepartmentService;

import java.util.List;

@Api(tags = "部门管理")
@RestController
@RequestMapping("/dep")
public class DepartmentController {
    @Autowired
    private DepartmentService departmentService;

    @ApiOperation(value = "查询部门列表")
    @GetMapping
    @PreAuthorize("hasAuthority('sys:department:select')")
    public R<List<DepartmentVO>> find(DepartmentQuery departmentQuery) {
        List<DepartmentPO> departmentPOS = departmentService.findDepartmentPO(departmentQuery);
        return R.ok(DepartmentVO.departmentPOToDepartmentVO(departmentPOS));
    }

    @GetMapping("/{id}")
    @ApiOperation(value = "获取部门详情")
    @PreAuthorize("hasAuthority('sys:department:select')")
    public R<OutDepartmentVO> getDepartmentById(@PathVariable(value = "id", required = true) String id) {
        return R.ok(BeanUtil.toBean(departmentService.getDepartmentPOById(id), OutDepartmentVO.class));
    }

    @ApiOperation(value = "新增部门")
    @PostMapping
    @PreAuthorize("hasAuthority('sys:department:create')")
    public R save(@Validated(value = {InsertGroup.class}) InDepartmentVO inDepartmentVO) {
        departmentService.saveDepartmentPO(BeanUtil.toBean(inDepartmentVO, DepartmentPO.class));
        return R.ok();
    }

    @ApiOperation(value = "修改部门")
    @PutMapping
    @PreAuthorize("hasAuthority('sys:department:update')")
    public R update(@Validated(value = {UpdateGroup.class}) InDepartmentVO inDepartmentVO) {
        departmentService.updateDepartmentPOById(BeanUtil.toBean(inDepartmentVO, DepartmentPO.class));
        return R.ok();
    }

    @ApiOperation(value = "删除部门")
    @DeleteMapping("/{id}")
    @PreAuthorize("hasAuthority('sys:department:delete')")
    public R delete(@PathVariable(value = "id", required = true) String id) {
        departmentService.deleteDepartmentById(id);
        return R.ok();
    }

    @ApiOperation(value="获取树形部门")
    @GetMapping("tree")
    public R<SelectTreeVO> findTree(){
        return R.ok(departmentService.findSelectVOAll());
    }
}
